package org.darkforest.common.services.impl;

import org.apache.commons.lang.StringUtils;
import org.darkforest.common.constant.Constants;
import org.darkforest.common.services.CartService;
import org.darkforest.common.services.CheckoutService;
import org.darkforest.common.services.SimpleRedisService;
import org.darkforest.common.services.TransportService;
import org.darkforest.common.util.JSONUtils;
import org.darkforest.dao.mapper.EnumParamMapper;
import org.darkforest.dao.mapper.GoodsMapper;
import org.darkforest.dao.mapper.MemberMapper;
import org.darkforest.model.Address;
import org.darkforest.model.Cart;
import org.darkforest.model.EnumParam;
import org.darkforest.model.Goods;
import org.darkforest.model.Member;
import org.darkforest.model.MemberWithBLOBs;
import org.darkforest.ucenter.service.AddressService;
import org.darkforest.vo.CartInfoAjaxVo;
import org.darkforest.vo.TransportFeeQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auth bingo
 * @create 2017-11-28-15:53
 */
@Service
public class CheckoutServiceImpl implements CheckoutService {

    @Autowired
    private AddressService addressService;

    @Autowired
    private CartService cartService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private TransportService transportService;

    @Autowired
    private SimpleRedisService simpleRedisService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private EnumParamMapper enumParamMapper;


    @Override
    public Map orderCheckout(Member member, Integer addressId, Integer qrcodeNum, Integer buyType, Integer cartChannel) {
        Map<String, Object> map = new HashMap();

        // 员工折扣
        BigDecimal empDiscount = new BigDecimal(100);
        // 员工级别的取得
        MemberWithBLOBs memberInfo = memberMapper.selectByPrimaryKey(member.getMemberId());
        Integer employeeLevel = memberInfo.getEmployeeLevel();
        if (employeeLevel != null && employeeLevel > 0) {
            // 员工折扣的取得
            EnumParam enumParam = new EnumParam();
            enumParam.setPageSwitch(false);
            enumParam.setParamType("employee_Level");
            String empLevel = "V" + employeeLevel;
            enumParam.setParamKey(empLevel);
            enumParam.setParamState(1);
            List<EnumParam> list = enumParamMapper.selectListByCondition(enumParam);
            if ((list != null) && (list.size() > 0)) {
                empDiscount = new BigDecimal(list.get(0).getParamValue());
            }
            map.put("isEmployee", 1);
        } else {
            map.put("isEmployee", 0);
        }

        if (cartChannel == 1) {
            // 目前将运费设置为0 （和以下第122行处理项对应）
//            //查询用户默认地址用来计算运费
//            Address address = addressService.getAddressById(addressId, member.getMemberId());
//            if (address == null) {
//                map.put("msg", Constants.ERROR_ADDRESS);
//                map.put("result", "false");
//                return map;
//            }

            //查询购物车内已经勾选的商品
            List<Integer> storeIds = cartService.findStoreByUserBuyGoods(member.getMemberId());
            if (storeIds.size() < 1) {
                map.put("msg", Constants.ERROR_EMPTY_CART);
                map.put("result", "false");
                return map;
            }
            //运费
            BigDecimal orderShip = new BigDecimal(0);
            //总价
            BigDecimal subtotal = new BigDecimal(0);

            for (Integer storeId : storeIds) {
                //获取用户在该店铺的所有勾选中的购物车商品
                List<Cart> simpleStoreCart = cartService.findCartList(member.getMemberId().toString(), "1", storeId);
                CartInfoAjaxVo cartInfo = new CartInfoAjaxVo(simpleStoreCart);
                subtotal = subtotal.add(cartInfo.getSubtotal());
                if (cartInfo.getList().size() < 1) {
                    map.put("msg", Constants.ERROR_EMPTY_CART);
                    map.put("result", "false");
                    return map;
                } else {
                    List<TransportFeeQuery> tsParam = new ArrayList<TransportFeeQuery>();                 //查询商品运费模板的参数
                    //获取商品总数量
                    for (Cart cart : cartInfo.getList()) {
                        Goods goods = goodsMapper.getGoodsById(cart.getGoodsId());
                        tsParam.add(new TransportFeeQuery(cart.getStoreId(), goods.getGoodsId(), goods.getGoodsPrice(), cart.getGoodsNum().intValue(), goods.getTransportId(), goods.getGoodsFreight()));
                    }
//                orderShip = orderShip.add(transportService.getTransportFee(address, tsParam,storeId));              //计算运费
                    orderShip = new BigDecimal(0); //目前将运费设置为0
                }
            }

            //如果是赠送的方式 则需要统计赠送的份数 （不是购物车内商品数量，）
            if (2 == buyType) {
                subtotal = subtotal.multiply(new BigDecimal(qrcodeNum));
//            orderShip = orderShip.multiply(new BigDecimal(qrcodeNum));
                orderShip = new BigDecimal(0); //目前将运费设置为0
            }

            map.put("cartTotalAmount", subtotal);
            // 员工价
            if (empDiscount.compareTo(new BigDecimal(100)) < 0) {
                subtotal = subtotal.multiply(empDiscount).divide(new BigDecimal(100));
            }
            map.put("empAmount", subtotal);
            map.put("totalAmount", subtotal.add(orderShip));
            map.put("shipAmount", orderShip);
            map.put("result", "true");

        } else {
            String carts = simpleRedisService.getByKey(member.getMemberId() + "_buy_goods");

            if (StringUtils.isNotBlank(carts)) {
//              JSONObject jsonObject = JSONObject.fromObject(carts);
                Cart cart = JSONUtils.toBean(carts, Cart.class);
                map.put("cartTotalAmount", cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNum())));
                //map.put("totalAmount", cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNum())));
                // 员工价
                BigDecimal subtotal = cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNum()));
                if (empDiscount.compareTo(new BigDecimal(100)) < 0) {
                    subtotal = subtotal.multiply(empDiscount).divide(new BigDecimal(100));
                }
                //subtotal = subtotal.setScale(2);
                map.put("empAmount", subtotal);
                map.put("totalAmount", subtotal);
                map.put("shipAmount", new BigDecimal(0));
                map.put("result", "true");
            } else {
                map.put("msg", Constants.ERROR_EMPTY_CART);
                map.put("result", "false");
            }
        }
        return map;
    }

    /**
     * 根据不同的店铺id计算对应商品的运费以及商品总价
     *
     * @param member
     * @param addressId
     * @param postType
     * @param cartChannel
     * @param storeId
     * @return
     */
    @Override
    public Map orderCheckoutBySimpleStore(Member member, Integer addressId, Integer qrcodeNum, Integer postType, Integer cartChannel, Integer storeId) {
        Map<String, Object> map = new HashMap();

        // 员工折扣
        BigDecimal empDiscount = new BigDecimal(100);
        // 员工级别的取得
        MemberWithBLOBs memberInfo = memberMapper.selectByPrimaryKey(member.getMemberId());
        Integer employeeLevel = memberInfo.getEmployeeLevel();
        if (employeeLevel != null && employeeLevel > 0) {
            // 员工折扣的取得
            EnumParam enumParam = new EnumParam();
            enumParam.setPageSwitch(false);
            enumParam.setParamType("employee_Level");
            String empLevel = "V" + employeeLevel;
            enumParam.setParamKey(empLevel);
            enumParam.setParamState(1);
            List<EnumParam> list = enumParamMapper.selectListByCondition(enumParam);
            if ((list != null) && (list.size() > 0)) {
                empDiscount = new BigDecimal(list.get(0).getParamValue());
            }
            map.put("isEmployee", 1);
        } else {
            map.put("isEmployee", 0);
        }

        if (cartChannel == 1) {
            // 目前将运费设置为0 （和以下第244行处理项对应）
//            //查询用户默认地址用来计算运费
//            Address address = addressService.getAddressById(addressId, member.getMemberId());
//            if (address == null) {
//                map.put("msg", Constants.ERROR_ADDRESS);
//                map.put("result", "false");
//                return map;
//            }

            //查询购物车内已经勾选的商品
            List<Integer> storeIds = cartService.findStoreByUserBuyGoods(member.getMemberId());
            if (storeIds.size() < 1) {
                map.put("msg", Constants.ERROR_EMPTY_CART);
                map.put("result", "false");
                return map;
            }

            //运费
            BigDecimal orderShip = new BigDecimal(0);
            //总价
            BigDecimal subtotal = new BigDecimal(0);

            //获取用户在该店铺的所有勾选中的购物车商品
            List<Cart> simpleStoreCart = cartService.findCartList(member.getMemberId().toString(), "1", storeId);
            CartInfoAjaxVo cartInfo = new CartInfoAjaxVo(simpleStoreCart);
            subtotal = subtotal.add(cartInfo.getSubtotal());
            if (cartInfo.getList().size() < 1) {
                map.put("msg", Constants.ERROR_EMPTY_CART);
                map.put("result", "false");
                return map;
            } else {
                List<TransportFeeQuery> tsParam = new ArrayList<TransportFeeQuery>();                 //查询商品运费模板的参数
                //获取商品总数量
                for (Cart cart : cartInfo.getList()) {
                    Goods goods = goodsMapper.getGoodsById(cart.getGoodsId());
                    tsParam.add(new TransportFeeQuery(cart.getStoreId(), goods.getGoodsId(), goods.getGoodsPrice(), cart.getGoodsNum().intValue(), goods.getTransportId(), goods.getGoodsFreight()));
                }
//                orderShip = orderShip.add(transportService.getTransportFee(address, tsParam,storeId));              //计算运费
                orderShip = new BigDecimal(0); //目前将运费设置为0
            }

            //如果是赠送的方式 则需要统计赠送的份数 （不是购物车内商品数量，）
            if (2 == postType) {
                subtotal = subtotal.multiply(new BigDecimal(qrcodeNum));
//            orderShip = orderShip.multiply(new BigDecimal(qrcodeNum));
                orderShip = new BigDecimal(0); //目前将运费设置为0
            }

            map.put("cartTotalAmount", subtotal);
            // 员工价
            if (empDiscount.compareTo(new BigDecimal(100)) < 0) {
                subtotal = subtotal.multiply(empDiscount).divide(new BigDecimal(100));
            }
            map.put("empAmount", subtotal);
            map.put("totalAmount", subtotal.add(orderShip));
            map.put("shipAmount", orderShip);
            map.put("result", "true");
        } else {
            String carts = simpleRedisService.getByKey(member.getMemberId() + "_buy_goods");
            if (StringUtils.isNotBlank(carts)) {
//              JSONObject jsonObject = JSONObject.fromObject(carts);
                Cart cart = JSONUtils.toBean(carts, Cart.class);

                //map.put("cartTotalAmount", cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNum())));
                //map.put("totalAmount", cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNum())));
                BigDecimal subtotal = cart.getGoodsPrice().multiply(new BigDecimal(cart.getGoodsNum()));
                map.put("cartTotalAmount", subtotal);
                // 员工价
                if (empDiscount.compareTo(new BigDecimal(100)) < 0) {
                    subtotal = subtotal.multiply(empDiscount).divide(new BigDecimal(100));
                }
                //subtotal = subtotal.setScale(2);
                map.put("empAmount", subtotal);
                map.put("totalAmount", subtotal);
                map.put("shipAmount", new BigDecimal(0));
                map.put("result", "true");
            } else {
                map.put("msg", Constants.ERROR_EMPTY_CART);
                map.put("result", "false");
            }
        }
        return map;
    }
}
